// 电荷交互物理模拟游戏
class ChargeSimulation {
    constructor() {
        this.canvas = document.getElementById('simulationCanvas');
        this.fieldLinesGroup = document.getElementById('fieldLinesGroup');
        this.forceVectorsGroup = document.getElementById('forceVectorsGroup');
        this.chargesGroup = document.getElementById('chargesGroup');
        
        this.charges = [];
        this.isPaused = false;
        this.isDragging = false;
        this.draggedCharge = null;
        
        this.chargeValue = 5; // nC
        this.k = 8.99e9; // 库仑常数 N·m²/C²
        
        this.init();
    }
    
    init() {
        this.setupEventListeners();
        this.updateDisplay();
        this.animate();
    }
    
    setupEventListeners() {
        // 添加电荷按钮
        document.getElementById('addPositive').addEventListener('click', () => {
            this.addCharge('positive');
        });
        
        document.getElementById('addNegative').addEventListener('click', () => {
            this.addCharge('negative');
        });
        
        // 电荷量滑块
        document.getElementById('chargeSlider').addEventListener('input', (e) => {
            this.chargeValue = parseInt(e.target.value);
            document.getElementById('chargeValue').textContent = this.chargeValue;
        });
        
        // 显示选项
        document.getElementById('showFieldLines').addEventListener('change', () => {
            this.updateDisplay();
        });
        
        document.getElementById('showForceVectors').addEventListener('change', () => {
            this.updateDisplay();
        });
        
        document.getElementById('showPotential').addEventListener('change', () => {
            this.updateDisplay();
        });
        
        // 控制按钮
        document.getElementById('pauseBtn').addEventListener('click', () => {
            this.togglePause();
        });
        
        document.getElementById('resetBtn').addEventListener('click', () => {
            this.reset();
        });
        
        // 画布事件
        this.canvas.addEventListener('mousedown', (e) => this.handleMouseDown(e));
        this.canvas.addEventListener('mousemove', (e) => this.handleMouseMove(e));
        this.canvas.addEventListener('mouseup', (e) => this.handleMouseUp(e));
        this.canvas.addEventListener('contextmenu', (e) => e.preventDefault());
    }
    
    addCharge(type) {
        const rect = this.canvas.getBoundingClientRect();
        const x = rect.width / 2 + (Math.random() - 0.5) * 200;
        const y = rect.height / 2 + (Math.random() - 0.5) * 200;
        
        const charge = {
            id: Date.now(),
            type: type,
            value: this.chargeValue * 1e-9, // 转换为库仑
            x: x,
            y: y,
            vx: 0,
            vy: 0,
            element: null
        };
        
        this.charges.push(charge);
        this.createChargeElement(charge);
        this.updateDisplay();
    }
    
    createChargeElement(charge) {
        const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
        circle.setAttribute('r', '20');
        circle.setAttribute('fill', charge.type === 'positive' ? '#EF4444' : '#2563EB');
        circle.setAttribute('stroke', '#1F2937');
        circle.setAttribute('stroke-width', '2');
        circle.setAttribute('cx', charge.x);
        circle.setAttribute('cy', charge.y);
        circle.setAttribute('class', 'charge');
        circle.setAttribute('data-id', charge.id);
        
        // 添加电荷符号
        const text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
        text.setAttribute('x', charge.x);
        text.setAttribute('y', charge.y + 5);
        text.setAttribute('text-anchor', 'middle');
        text.setAttribute('font-size', '16');
        text.setAttribute('font-weight', 'bold');
        text.setAttribute('fill', 'white');
        text.textContent = charge.type === 'positive' ? '+' : '−';
        
        this.chargesGroup.appendChild(circle);
        this.chargesGroup.appendChild(text);
        
        charge.element = circle;
        charge.textElement = text;
    }
    
    handleMouseDown(e) {
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        const clickedCharge = this.getChargeAt(x, y);
        if (clickedCharge) {
            this.isDragging = true;
            this.draggedCharge = clickedCharge;
        }
    }
    
    handleMouseMove(e) {
        if (!this.isDragging || !this.draggedCharge) return;
        
        const rect = this.canvas.getBoundingClientRect();
        const x = e.clientX - rect.left;
        const y = e.clientY - rect.top;
        
        this.draggedCharge.x = Math.max(20, Math.min(x, rect.width - 20));
        this.draggedCharge.y = Math.max(20, Math.min(y, rect.height - 20));
        
        this.updateChargePosition(this.draggedCharge);
        this.updateDisplay();
    }
    
    handleMouseUp(e) {
        this.isDragging = false;
        this.draggedCharge = null;
    }
    
    getChargeAt(x, y) {
        return this.charges.find(charge => {
            const dx = x - charge.x;
            const dy = y - charge.y;
            return Math.sqrt(dx * dx + dy * dy) < 25;
        });
    }
    
    updateChargePosition(charge) {
        if (charge.element) {
            charge.element.setAttribute('cx', charge.x);
            charge.element.setAttribute('cy', charge.y);
        }
        if (charge.textElement) {
            charge.textElement.setAttribute('x', charge.x);
            charge.textElement.setAttribute('y', charge.y + 5);
        }
    }
    
    calculateForces() {
        if (this.isPaused) return;
        
        for (let i = 0; i < this.charges.length; i++) {
            const charge1 = this.charges[i];
            let fx = 0, fy = 0;
            
            for (let j = 0; j < this.charges.length; j++) {
                if (i === j) continue;
                
                const charge2 = this.charges[j];
                const dx = charge2.x - charge1.x;
                const dy = charge2.y - charge1.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance < 40) continue; // 防止重叠
                
                const force = this.k * Math.abs(charge1.value * charge2.value) / (distance * distance);
                const direction = (charge1.value * charge2.value > 0) ? -1 : 1;
                
                fx += direction * force * dx / distance;
                fy += direction * force * dy / distance;
            }
            
            // 简化的运动模拟
            const damping = 0.95;
            charge1.vx = (charge1.vx + fx * 0.01) * damping;
            charge1.vy = (charge1.vy + fy * 0.01) * damping;
            
            if (!this.isDragging || charge1 !== this.draggedCharge) {
                charge1.x += charge1.vx;
                charge1.y += charge1.vy;
                
                // 边界碰撞
                const rect = this.canvas.getBoundingClientRect();
                if (charge1.x < 20 || charge1.x > rect.width - 20) {
                    charge1.vx *= -0.8;
                    charge1.x = Math.max(20, Math.min(charge1.x, rect.width - 20));
                }
                if (charge1.y < 20 || charge1.y > rect.height - 20) {
                    charge1.vy *= -0.8;
                    charge1.y = Math.max(20, Math.min(charge1.y, rect.height - 20));
                }
                
                this.updateChargePosition(charge1);
            }
        }
    }
    
    drawFieldLines() {
        if (!document.getElementById('showFieldLines').checked) {
            this.fieldLinesGroup.innerHTML = '';
            return;
        }
        
        this.fieldLinesGroup.innerHTML = '';
        
        if (this.charges.length < 2) return;
        
        // 简化的电场线绘制
        const rect = this.canvas.getBoundingClientRect();
        const step = 40;
        
        for (let x = step; x < rect.width; x += step) {
            for (let y = step; y < rect.height; y += step) {
                let ex = 0, ey = 0;
                
                for (const charge of this.charges) {
                    const dx = x - charge.x;
                    const dy = y - charge.y;
                    const distance = Math.sqrt(dx * dx + dy * dy);
                    
                    if (distance < 30) continue;
                    
                    const field = this.k * charge.value / (distance * distance);
                    ex += field * dx / distance;
                    ey += field * dy / distance;
                }
                
                const magnitude = Math.sqrt(ex * ex + ey * ey);
                if (magnitude > 1e-8) {
                    const length = 20;
                    const endX = x + (ex / magnitude) * length;
                    const endY = y + (ey / magnitude) * length;
                    
                    const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
                    line.setAttribute('x1', x);
                    line.setAttribute('y1', y);
                    line.setAttribute('x2', endX);
                    line.setAttribute('y2', endY);
                    line.setAttribute('class', 'field-line');
                    
                    this.fieldLinesGroup.appendChild(line);
                }
            }
        }
    }
    
    drawForceVectors() {
        if (!document.getElementById('showForceVectors').checked) {
            this.forceVectorsGroup.innerHTML = '';
            return;
        }
        
        this.forceVectorsGroup.innerHTML = '';
        
        for (const charge of this.charges) {
            let fx = 0, fy = 0;
            
            for (const other of this.charges) {
                if (charge === other) continue;
                
                const dx = other.x - charge.x;
                const dy = other.y - charge.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance < 40) continue;
                
                const force = this.k * Math.abs(charge.value * other.value) / (distance * distance);
                const direction = (charge.value * other.value > 0) ? -1 : 1;
                
                fx += direction * force * dx / distance;
                fy += direction * force * dy / distance;
            }
            
            const scale = 1e-10;
            const arrowLength = Math.sqrt(fx * fx + fy * fy) * scale;
            
            if (arrowLength > 5) {
                const angle = Math.atan2(fy, fx);
                const endX = charge.x + arrowLength * Math.cos(angle);
                const endY = charge.y + arrowLength * Math.sin(angle);
                
                const line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
                line.setAttribute('x1', charge.x);
                line.setAttribute('y1', charge.y);
                line.setAttribute('x2', endX);
                line.setAttribute('y2', endY);
                line.setAttribute('stroke', '#10B981');
                line.setAttribute('stroke-width', '2');
                line.setAttribute('marker-end', 'url(#arrowhead)');
                
                this.forceVectorsGroup.appendChild(line);
            }
        }
        
        // 添加箭头标记
        if (!document.getElementById('arrowhead')) {
            const defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
            const marker = document.createElementNS('http://www.w3.org/2000/svg', 'marker');
            marker.setAttribute('id', 'arrowhead');
            marker.setAttribute('markerWidth', '10');
            marker.setAttribute('markerHeight', '7');
            marker.setAttribute('refX', '9');
            marker.setAttribute('refY', '3.5');
            marker.setAttribute('orient', 'auto');
            
            const polygon = document.createElementNS('http://www.w3.org/2000/svg', 'polygon');
            polygon.setAttribute('points', '0 0, 10 3.5, 0 7');
            polygon.setAttribute('fill', '#10B981');
            
            marker.appendChild(polygon);
            defs.appendChild(marker);
            this.canvas.appendChild(defs);
        }
    }
    
    calculatePotentialEnergy() {
        let totalPotential = 0;
        let totalCharge = 0;
        
        for (let i = 0; i < this.charges.length; i++) {
            totalCharge += this.charges[i].value * 1e9; // 转换回nC
            
            for (let j = i + 1; j < this.charges.length; j++) {
                const charge1 = this.charges[i];
                const charge2 = this.charges[j];
                
                const dx = charge2.x - charge1.x;
                const dy = charge2.y - charge1.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                if (distance > 0) {
                    const potential = this.k * charge1.value * charge2.value / distance;
                    totalPotential += potential;
                }
            }
        }
        
        document.getElementById('totalCharge').textContent = totalCharge.toFixed(1) + ' nC';
        document.getElementById('totalPotential').textContent = (totalPotential * 1e9).toFixed(2) + ' nJ';
        document.getElementById('chargeCount').textContent = this.charges.length;
    }
    
    updateDisplay() {
        this.drawFieldLines();
        this.drawForceVectors();
        this.calculatePotentialEnergy();
    }
    
    togglePause() {
        this.isPaused = !this.isPaused;
        const pauseBtn = document.getElementById('pauseBtn');
        pauseBtn.innerHTML = this.isPaused ? 
            '<i class="fa fa-play mr-1"></i>继续' : 
            '<i class="fa fa-pause mr-1"></i>暂停';
    }
    
    reset() {
        this.charges = [];
        this.chargesGroup.innerHTML = '';
        this.fieldLinesGroup.innerHTML = '';
        this.forceVectorsGroup.innerHTML = '';
        this.updateDisplay();
    }
    
    animate() {
        if (!this.isPaused) {
            this.calculateForces();
            this.updateDisplay();
        }
        requestAnimationFrame(() => this.animate());
    }
}

// 初始化模拟
document.addEventListener('DOMContentLoaded', () => {
    const simulation = new ChargeSimulation();
    
    // 添加示例电荷
    simulation.addCharge('positive');
    simulation.addCharge('negative');
});